package com.wakyde.unsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.ConcurrentHashMap;

public class CasTest {
    private volatile int a;

    public static void main(String[] args) {
        CasTest casTest = new CasTest();
        new Thread(()->{
            for (int i = 1; i < 5; i++) {
                casTest.increment(i);
                System.out.print(casTest.a+" ");
            }
        }).start();
    }

    private void increment(int x){
        Unsafe unsafe = null;
        try {
            unsafe = CasTest.reflectGetUnsafe();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        while (true){
            try {
                long fieldOffset = unsafe.objectFieldOffset(CasTest.class.getDeclaredField("a"));
                if (unsafe.compareAndSwapInt(this,fieldOffset,x-1,x))
                    break;
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
    }

    //引用Unsafe需使用如下反射方式，否则会抛出异常java.lang.SecurityException: Unsafe
    public static Unsafe reflectGetUnsafe() throws NoSuchFieldException, IllegalAccessException {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);//禁止访问权限检查（访问私有属性时需要加上）
        return (Unsafe) theUnsafe.get(null);
    }


}
